package com.lazymc.recoredutils.utils;

import android.content.Context;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.os.RemoteException;
import android.text.format.Formatter;

import com.lazymc.recoredutils.AppBean;
import com.lazymc.recoredutils.ContentFragment;
import com.lazymc.recoredutils.Service;
import com.lazymc.recoredutils.provider.BusProvider;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dzj on 2016/1/6.
 */
public class FindAppsUtils {

    public static void findApps(final Context context){
        Runnable runnable= () -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            List<PackageInfo> list = context.getPackageManager().getInstalledPackages(0);
            if (list!=null) {
                List<AppBean> beanList = new ArrayList<>(list.size());
                AppBean bean=null;
                PackageInfo info=null;
                PackageManager pManager =context.getPackageManager();
                for (int i=0;i<list.size();i++){
                    bean=new AppBean();
                    info=list.get(i);
                    bean.setIcon(pManager.getApplicationIcon(info.applicationInfo));
                    bean.setId(info.packageName.hashCode());
                    bean.setName(pManager.getApplicationLabel(info.applicationInfo).toString());
                    bean.setPkg(info.applicationInfo.packageName);
//                        try {
//                            queryPacakgeSize(bean,context);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
                    beanList.add(bean);
                }
                BusProvider.getInstance().posts(beanList);
            }
        };
        Service.exe(runnable);
    }

    public interface CallBack{
        void callBack(List<AppBean> beanList);
    }


    public static void  queryPacakgeSize(AppBean pkgName,Context context) throws Exception{
        if ( pkgName != null){
            //使用放射机制得到PackageManager类的隐藏函数getPackageSizeInfo
            PackageManager pm = context.getPackageManager();  //得到pm对象
            try {
                //通过反射机制获得该隐藏函数
                Method getPackageSizeInfo = pm.getClass().getDeclaredMethod("getPackageSizeInfo", String.class,IPackageStatsObserver.class);
                //调用该函数，并且给其分配参数 ，待调用流程完成后会回调PkgSizeObserver类的函数
                PkgSizeObserver observer = new PkgSizeObserver();
                observer.ctx=context;
                observer.pkgName=pkgName;
                getPackageSizeInfo.invoke(pm, pkgName.getPkg(),observer);
            }
            catch(Exception ex){
               // Log.e(TAG, "NoSuchMethodException") ;
                ex.printStackTrace() ;
                throw ex ;  // 抛出异常
            }
        }
    }

    //aidl文件形成的Bindler机制服务类
    public static class PkgSizeObserver extends IPackageStatsObserver.Stub{
        private Context ctx;
        private AppBean pkgName;
        /*** 回调函数，
         * @param succeeded  代表回调成功
         */
        @Override
        public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
                throws RemoteException {
            // TODO Auto-generated method stub
            long cachesize = pStats.cacheSize;; //缓存大小
            long datasize = pStats.dataSize;;  //数据大小
            long codesize = pStats.codeSize;;  //应用程序大小
            long totalsize = cachesize + datasize + codesize;
            String totalStr=formateFileSize(totalsize,ctx);
            pkgName.setTotalSize(totalStr);
            BusProvider.getInstance().posts(ContentFragment.class);
            // Log.i(TAG, "cachesize--->"+cachesize+" datasize---->"+datasize+ " codeSize---->"+codesize)  ;
        }
    }
    //系统函数，字符串转换 long -String (kb)
    private static String formateFileSize(long size,Context context){
        return Formatter.formatFileSize(context, size);
    }
    // 获得所有启动Activity的信息，类似于Launch界面
    public void queryAppInfo(Context context) {
//        PackageManager pm = context.getPackageManager(); // 获得PackageManager对象
//        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
//        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//        // 通过查询，获得所有ResolveInfo对象.
//        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(mainIntent, 0);
//        // 调用系统排序 ， 根据name排序
//        // 该排序很重要，否则只能显示系统应用，而不能列出第三方应用程序
//        Collections.sort(resolveInfos, new ResolveInfo.DisplayNameComparator(pm));
//        if (mlistAppInfo != null) {
//            mlistAppInfo.clear();
//            for (ResolveInfo reInfo : resolveInfos) {
//                String activityName = reInfo.activityInfo.name; // 获得该应用程序的启动Activity的name
//                String pkgName = reInfo.activityInfo.packageName; // 获得应用程序的包名
//                String appLabel = (String) reInfo.loadLabel(pm); // 获得应用程序的Label
//                Drawable icon = reInfo.loadIcon(pm); // 获得应用程序图标
//                // 为应用程序的启动Activity 准备Intent
//                Intent launchIntent = new Intent();
//                launchIntent.setComponent(new ComponentName(pkgName,activityName));
//                // 创建一个AppInfo对象，并赋值
////                AppInfo appInfo = new AppInfo();
////                appInfo.setAppLabel(appLabel);
////                appInfo.setPkgName(pkgName);
////                appInfo.setAppIcon(icon);
////                appInfo.setIntent(launchIntent);
////                mlistAppInfo.add(appInfo); // 添加至列表中
//            }
//        }
    }

}
